<template>
  <div class="role-page-com">
    <div class="filter-contain">
      <el-form
        ref="queryFormRef"
        :model="queryForm"
        label-width="80px"
        label-position="right"
        class="role-filter-form"
        :inline="true"
      >
        <el-form-item prop="roleCode" label="角色编号" class="form-input">
          <el-input
            v-model="queryForm.roleCode"
            placeholder="请输入角色编号"
          ></el-input>
        </el-form-item>
        <el-form-item prop="roleName" label="角色名称" class="form-input">
          <el-input
            v-model="queryForm.roleName"
            placeholder="请输入角色名称"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            :loading="tableLoading"
            @click="handleQuery"
          >
            <template #icon>
              <i-ep-search />
            </template>
            查询</el-button
          >
          <el-button
            type="default"
            @click="handleReset"
            :loading="tableLoading"
          >
            <template #icon>
              <i-ep-refreshLeft />
            </template>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="table-btn-contain">
      <el-button type="primary" @click="handleAdd">
        <template #icon>
          <i-ep-plus />
        </template>
        新增
      </el-button>
      <el-dropdown @command="handleStatusCommand">
        <el-button type="default">
          <template #icon>
            <i-ep-editPen />
          </template>
          状态变更
        </el-button>
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item command="0">开启</el-dropdown-item>
            <el-dropdown-item command="1">禁用</el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>
    </div>
    <div class="table-contain">
      <kt-table
        :tableData="tableData"
        :tableColumns="tableColumns"
        :page-number="queryForm.pageNumber"
        :page-size="queryForm.pageSize"
        :total="queryForm.total"
        showPagination
        @selection-change="handleSelectionChange"
        @getList="getList"
      >
        <template #roleStatusStr="{ row }">
          <el-tag
            v-if="row.roleStatus === '0'"
            type="success"
            size="default"
            class="table-tag"
            >{{ row.roleStatusStr }}</el-tag
          >
          <el-tag
            v-else-if="row.roleStatus === '1'"
            type="danger"
            size="default"
            class="table-tag"
            >{{ row.roleStatusStr }}</el-tag
          >
        </template>
        <template #action="{ row }">
          <el-button
            type="primary"
            @click="handleEdit(row)"
            class="table-btn"
            link
          >
            <template #icon>
              <i-ep-edit />
            </template>
            编辑
          </el-button>
          <el-button
            type="primary"
            @click="handleView(row)"
            class="table-btn"
            link
          >
            <template #icon>
              <i-ep-view />
            </template>
            查看
          </el-button>
        </template>
      </kt-table>
    </div>
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      :before-close="clearDialog"
      width="600px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <el-form
        ref="dialogFormRef"
        :model="dialogForm"
        label-width="80px"
        label-position="right"
        :disabled="dialogType === 2"
        inline
        :rules="dialogFormRules"
        class="dialog-role-form"
      >
        <el-form-item prop="roleCode" label="角色编号" class="form-input">
          <el-input
            :disabled="dialogType !== 0"
            v-model="dialogForm.roleCode"
            placeholder="请输入角色编号"
          ></el-input>
        </el-form-item>
        <el-form-item prop="roleName" label="角色名称" class="form-input">
          <el-input
            v-model="dialogForm.roleName"
            placeholder="请输入角色名称"
          ></el-input>
        </el-form-item>
        <el-form-item
          prop="description"
          label="描述"
          class="form-input"
          w-555px
        >
          <el-input
            v-model="dialogForm.description"
            :autosize="{ minRows: 2, maxRows: 4 }"
            type="textarea"
            placeholder="请输入描述"
          ></el-input>
        </el-form-item>
        <el-form-item label="角色状态" class="form-input">
          <el-radio-group
            v-model="dialogForm.roleStatus"
            :disabled="dialogType !== 1"
          >
            <el-radio label="0">启用</el-radio>
            <el-radio label="1">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button :loading="submitLoading" @click="closeDialog"
          >取消</el-button
        >
        <el-button :loading="submitLoading" type="primary" @click="handleSubmit"
          >确定</el-button
        >
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { getRoleInfo, addRole, updateRole, updateRoleStatus } from "@/api/role"
import { ElMessage } from "element-plus"

// 定义初始表单对象副本
const initialQueryForm = {
  roleCode: "",
  roleName: "",
  pageSize: 20,
  pageNumber: 1,
  total: 0
}
const initialDialogForm = {
  roleCode: "",
  roleName: "",
  description: "",
  roleStatus: "0"
}

const selectedRows = ref<any[]>([])
const dialogVisible = ref(false)
const dialogTitle = ref("")
const dialogType = ref(0) // 0:新增 1:编辑 2:查看
const dialogFormRef = ref()
const dialogForm = ref({ ...initialDialogForm })
const dialogFormRules = {
  roleName: [{ required: true, message: "请输入角色编号", trigger: "blur" }],
  roleCode: [{ required: true, message: "请输入角色名称", trigger: "blur" }]
}
const submitLoading = ref(false)
const tableLoading = ref(false)
const tableData = ref([])
const queryFormRef = ref()
const queryForm = ref({ ...initialQueryForm })
const tableColumns = [
  {
    prop: "selection",
    type: "selection",
    width: "55px",
    fixed: "left"
  },
  {
    label: "角色编号",
    prop: "roleCode"
  },
  {
    label: "角色名称",
    prop: "roleName"
  },
  {
    label: "角色状态",
    prop: "roleStatusStr"
  },
  {
    label: "最近修改时间",
    prop: "updatedAt"
  },
  {
    label: "最近修改人",
    prop: "updatedUserStr"
  },
  {
    label: "创建时间",
    prop: "createdAt"
  },
  {
    label: "创建人",
    prop: "createdUserStr"
  },
  {
    label: "操作",
    prop: "action",
    width: "200px",
    fixed: "right",
    slotName: "action"
  }
]
// 条件查询
const handleQuery = () => {
  queryForm.value.pageNumber = 1
  getList({
    pageNumber: 1
  })
}
// 重置查询条件
const handleReset = () => {
  // 使用初始对象副本重置
  queryForm.value = { ...initialQueryForm, pageSize: queryForm.value.pageSize }
  const form = queryFormRef.value
  if (form) {
    form.resetFields()
  }
  getList()
}
// 选择条目
const handleSelectionChange = (rows: any[]) => {
  selectedRows.value = rows
}
// 处理状态变更
const handleStatusCommand = (status: string) => {
  handleStatusChange(status)
}
// 新增角色
const handleAdd = () => {
  dialogVisible.value = true
  dialogTitle.value = "新增角色"
  dialogType.value = 0
  // 使用初始对象副本重置
  dialogForm.value = { ...initialDialogForm }
  const form = dialogFormRef.value
  if (form) {
    form.clearValidate()
  }
}
// 编辑角色
const handleEdit = (row: any) => {
  dialogVisible.value = true
  dialogTitle.value = "编辑角色"
  dialogType.value = 1
  dialogForm.value = { ...row }
  const form = dialogFormRef.value
  if (form) {
    form.clearValidate()
  }
}
// 查看角色
const handleView = (row: any) => {
  dialogVisible.value = true
  dialogTitle.value = "查看角色"
  dialogType.value = 2
  dialogForm.value = { ...row }
  const form = dialogFormRef.value
  if (form) {
    form.clearValidate()
  }
}
// 弹窗确认
const handleSubmit = () => {
  const form = dialogFormRef.value
  if (form) {
    form.validate((valid: boolean) => {
      if (valid) {
        // 提交表单
        submitLoading.value = true
        try {
          if (dialogType.value === 0) {
            addRoleFn(dialogForm.value)
          } else if (dialogType.value === 1) {
            updateRoleFn(dialogForm.value)
          } else {
            dialogVisible.value = false
          }
        } catch (error) {
          ElMessage.error("提交失败，请稍后重试！")
          console.error(error) // eslint-disable-line
        } finally {
          submitLoading.value = false
        }
      } else {
        ElMessage.error("请填写完整信息")
      }
    })
  }
}
// 关闭弹窗
const closeDialog = () => {
  dialogVisible.value = false
  clearDialog()
}
// 关闭弹窗前的操作
const clearDialog = () => {
  // 使用初始对象副本重置
  dialogForm.value = { ...initialDialogForm }
  const form = dialogFormRef.value
  if (form) {
    form.resetFields()
  }
}
// 获取角色信息(param可选)
const getList = async (param: any = {}) => {
  const tempParam = param || {}
  queryForm.value = {
    ...queryForm.value,
    ...tempParam
  }
  tableLoading.value = true
  try {
    const res = await getRoleInfo(queryForm.value)
    tableData.value = res.data.rows
    queryForm.value.total = res.data.total
  } catch (error) {
    console.error(error) // eslint-disable-line
  } finally {
    tableLoading.value = false
  }
}
// 新增角色信息
const addRoleFn = async (data: any) => {
  try {
    const res = await addRole(data)
    if (res.code !== 0) {
      ElMessage.error(res.msg)
      return
    }
    ElMessage.success("新增成功")
    dialogVisible.value = false
    getList()
  } catch (error) {
    console.error(error) // eslint-disable-line
  }
}
// 编辑角色信息
const updateRoleFn = async (data: any) => {
  try {
    const res = await updateRole(data)
    if (res.code !== 0) {
      ElMessage.error(res.msg)
      return
    }
    ElMessage.success("编辑成功")
    dialogVisible.value = false
    getList()
  } catch (error) {
    console.error(error) // eslint-disable-line
  }
}
// 批量禁用/恢复角色

const handleStatusChange = async (status: string) => {
  if (selectedRows.value.length === 0) {
    ElMessage.error("请至少选择一条数据")
    return
  }
  try {
    const res = await updateRoleStatus({
      ids: selectedRows.value.map((item: any) => item.roleId),
      roleStatus: status
    })
    if (res.code !== 0) {
      ElMessage.error(res.msg)
      return
    }
    ElMessage.success("操作成功")
    getList()
  } catch (error) {
    console.error(error) // eslint-disable-line
  }
}

// 组件挂载后获取角色信息
onMounted(() => {
  getList()
})
</script>

<style lang="scss" scoped>
.role-page-com {
  height: 100%;
  @apply flex flex-col;
  .filter-contain {
    @apply h-auto;
    .user-filter-form {
      .filter-input {
        @apply w-200px;
      }
    }
  }
  .table-btn-contain {
    @apply h-auto pb-4;
    :deep(.el-button) {
      @apply mr-4;
    }
  }
  .table-contain {
    @apply flex-1;
  }
}
</style>
